<template>
  <div class="tab_profile">
    <div class="tab_inner">
      <div class="profile_left">
        <div class="profile_avatar">
          <img :src="getHeadIcon()"
               v-if="loginInfo.token">
        </div>
        <div class="profile_username"
             v-if="loginInfo.token"
             v-text="loginInfo.nickname || loginInfo.username"></div>

        <div class="profile_footer">
          <Button type="error"
                  v-if="!!loginInfo.token"
                  @click="logout">退出账号</Button>
          <Button type="primary"
                  v-else
                  @click="showLoginBox">登录</Button>
        </div>
      </div>
      <div class="profile_right">
        <Table :columns="column"
               border
               :data="myPlugins"></Table>
      </div>
    </div>

    <div class="register_box"
         ref="boxRef">
      <div class="register_box_mask"
           ref="maskRef"></div>
      <div class="register_box_content">
        <div class="register_box_content_inner"
             ref="innerRef">
          <RegisterBox v-if="actionName == 'register'"
                       @goto="goto"></RegisterBox>
          <LoginBox v-if="actionName == 'login'"
                    @goto="goto"
                    :default-username="loginInfo.phonenum"
                    :action-params="actionParams"
                    @login-success="loginSuccess"></LoginBox>
          <div class="close_btn"
               @click="hideLoginBox">
            <svg>
              <use xlink:href="#icon-close"></use>
            </svg>
          </div>
        </div>
      </div>
    </div>

    <!-- <transition name="fade">
      <div class="register_box"
           v-if="!loginInfo.token && showBox">
        <div class="register_box_mask"></div>
        <div class="register_box_content">
          <div class="register_box_content_inner">
            <RegisterBox v-if="actionName == 'register'"
                         @goto="goto"></RegisterBox>
            <LoginBox v-if="actionName == 'login'"
                      @goto="goto"
                      @login-success="loginSuccess"></LoginBox>
            <div class="close_btn"
                 @click="hideLoginBox">
              <svg>
                <use xlink:href="#icon-close"></use>
              </svg>
            </div>
          </div>
        </div>
      </div>
    </transition> -->

  </div>
</template>

<script>
import { Button, Table } from 'view-design'
import { createNamespacedHelpers, mapState } from 'vuex'
const { mapActions } = createNamespacedHelpers('./store/modules')
export default {
  name: 'Profile',
  components: {
    RegisterBox: () => import('./Register'),
    LoginBox: () => import('./Login'),
    Button, Table
  },
  props: {
    urlParams: {
      type: Object,
      default () {
        return {}
      }
    },
    activeTab: {
      type: String,
      default: ''
    }
  },
  watch: {
    urlParams: {
      immediate: true,
      deep: true,
      handler (val) {
        if (val.action && this.allAction.indexOf(val.action) > -1) {
          this.actionName = val.action
          this.showLoginBox()
        }
      }
    },
    activeTab: {
      immediate: true,
      handler (val) {
        if (val == 'Profile') {
          // this.loginInfo = this.$initLoginInfo()
          this.initMyPlugins()
        }
      }
    }
  },
  data () {
    return {
      allAction: ['login', 'register'],
      // loginInfo: {},
      actionName: 'login', // register: 显示注册窗口; login: 显示登录窗口; forget: 显示忘记密码窗口
      actionParams: {},
      myPlugins: [],
      viewStatus: {},
    }
  },
  computed: {
    ...mapState(
      {
        loginInfo: (state) => state.moduleUser.userInfo,
      }
    ),
    column () {
      return [
        {
          type: 'index',
          width: 50,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '插件名称',
          key: 'pluginName',
          width: 100,
          fixed: 'left'
        },
        {
          title: '版本号',
          key: 'version',
          width: 80
        },
        {
          title: '插件大小',
          key: 'size',
          width: 100,
          render: (h, params) => {
            return h('div', {}, this.$sizeFormat(params.row.size))
          }
        },
        {
          title: 'logo',
          key: 'logo',
          width: 80,
          render: (h, params) => {
            return h('div', {
              style: {
                width: '56px',
                height: '56px',
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center'
              }
            }, [
              h('img', {
                attrs: {
                  src: params.row.logo
                },
                style: {
                  width: '48px',
                  height: '48px',
                  borderRadius: '4px'
                }
              })
            ])
          }
        },
        {
          title: '作者',
          key: 'author',
          width: 80
        },
        {
          title: '提审时间',
          key: 'updatedAt',
          width: 120,
          render: (h, params) => {
            return h('div', {}, this.$timeFormat2(new Date(params.row.updatedAt).getTime()))
          }
        },
        {
          title: '描述',
          key: 'description',
          width: 180
        },
        {
          title: '预览',
          key: 'url',
          fixed: 'right',
          width: 100,
          render: (h, params) => {
            let _hash = (params.row.url.indexOf('?') > 0 ? ('_' + params.row.url.split('?')[1]) : '')
            if (this.viewStatus[params.row.pid + _hash] && this.viewStatus[params.row.pid + _hash].action == 'downloading') {
              return h('a', {}, this.viewStatus[params.row.pid + _hash].percent.toFixed(2) + '%')
            } else {
              return h('a', {
                href: '',
                on: {
                  click: () => {
                    let _d = Object.assign({}, params.row, {
                      features: params.row.features || {}
                    })
                    bbtools.send('rfc-view', _d)
                  }
                }
              }, '预览')
            }
          }
        },
        {
          title: '审核状态',
          key: 'status',
          fixed: 'right',
          width: 150,
          render: (h, params) => {
            if (params.row.status == 0) {
              return h('div', {
                style: {
                  color: '#2db7f5',
                  fontWeight: 'bold'
                }
              }, '未审核')
            } else if (params.row.status == 1) {
              return h('div', {
                style: {
                  color: 'green',
                  fontWeight: 'bold'
                }
              }, '审核通过')
            } else if (params.row.status == -1) {
              return h('div', {
                style: {
                  color: "#ff9900",
                  fontWeight: 'bold'
                }
              }, '审核未通过' + (params.row.errmsg ? ":【" + params.row.errmsg + "】" : ''))
            }
          }
        }
      ]
    }
  },
  mounted () {
    this.$nextTick(() => {
      bbtools.on('user-logout-response', this.userLogoutResponse)
      bbtools.on('user-login-response', this.userLoginResponse)
      // bbtools.on('login-info-updated', this.initLoginInfo)
      bbtools.on('rfc-list-my-plugins-response', this.listMyPluginsResponse)
      bbtools.on('rfc-view-response', this.rfcViewResponse)
    })
  },
  methods: {
    rfcViewResponse (event, response) {
      // this.viewStatus[response.id] = response
      if (response.code == 200) {
        if (response.data.action == 'done') {
          if (this.viewStatus[response.data.id]) {
            delete this.viewStatus[response.data.id]
          }
        } else {
          this.$set(this.viewStatus, response.data.id, response.data)
        }
      }

      // console.log('>>>>', this.viewStatus)
      // console.log(`${response.id} ${response.message} ${response.action == 'downloading' ? response.percent : ''}`)
    },
    initMyPlugins () {
      bbtools.send('rfc-list-my-plugins', this.loginInfo)
    },
    listMyPluginsResponse (event, myPlugins) {
      if (myPlugins.data && (myPlugins.code == 200)) {
        if (myPlugins.data.needLogin) {
          this.actionName = 'login'
          this.showLoginBox()
        } else if (myPlugins.data.needRegister) {
          this.actionName = 'register'
          this.showLoginBox()
        } else {
          this.myPlugins = myPlugins.data.list || []
        }
      }
    },
    goto (data) {
      if (!data.name) return
      this.actionName = data.name
      this.actionParams = data.params
    },
    loginSuccess (data) {
      // this.loginInfo = JSON.parse(JSON.stringify(data))
    },
    getHeadIcon () {
      let headIcon = ''
      if (this.loginInfo && this.loginInfo.headIcon) {
        headIcon = this.loginInfo.headIcon
      }
      if (!headIcon) {
        headIcon = ((!this.loginInfo || this.loginInfo.gender === 1) ? 'http://static.dei2.com/resources/avatar_male.jpg' : 'http://static.dei2.com/resources/avatar_female.jpg')
      }
      return headIcon
    },
    logout () {
      // this.hideLoginBox()
      bbtools.send('user-logout', this.loginInfo)
    },
    userLogoutResponse (event, response) {
      if (response.code == 200) {
        this.myPlugins = []
      }
    },
    hideLoginBox () {
      this.actionParams = {}
      // if (!this.loginInfo.token) {
      let boxRef = this.$refs.boxRef
      let maskRef = this.$refs.maskRef
      let innerRef = this.$refs.innerRef
      if (!boxRef || !maskRef || !innerRef) return
      innerRef.style.transform = 'translate3d(0, 800px, 0)'
      setTimeout(() => {
        maskRef.style.opacity = 0
        setTimeout(() => {
          boxRef.style.transform = 'scale(0)'
        }, 350)
      }, 150)
      // }
    },
    showLoginBox () {
      // if (!this.loginInfo.token) {
      let boxRef = this.$refs.boxRef
      let maskRef = this.$refs.maskRef
      let innerRef = this.$refs.innerRef
      if (!boxRef || !maskRef || !innerRef) return
      boxRef.style.transform = 'scale(1)'
      maskRef.style.transition = 'opacity .3s ease-in-out'
      maskRef.style.opacity = 1
      setTimeout(() => {
        innerRef.style.transition = 'all .3s ease-in-out'
        innerRef.style.transform = 'translate3d(0, 0, 0)'
      }, 150)
      // }
    },
    initLoginInfo () {
      this.loginInfo = this.$initLoginInfo()
    },
    userLoginResponse (event, res) {
      if (res.code === 200) {
        // 登录成功
        this.loginStatus = 1
        this.hideLoginBox()
        this.initMyPlugins()
        // this.loginInfo = res.data
        // bbtools.send('tray-login', this.loginInfo)
      } else {
        // 登录失败
        this.loginStatus = -1
      }
    },
  }
}
</script>

<style lang="less" scoped>
@import url("../../themes/index.less");
.slide-fade-enter-active {
  transition: all 0.25s linear;
}
.slide-fade-leave-active {
  transition: all 0.25s linear;
}
.slide-fade-enter, .slide-fade-leave-to
/* .slide-fade-leave-active for below version 2.1.8 */ {
  transform: translateY(100px);
  transition-delay: 200ms;
  opacity: 0;
}
.tab_profile {
  position: relative;
  width: 100%;
  height: 100%;
  .profile_avatar {
    width: 100%;
    height: 64px;
    margin-top: 30px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    img {
      width: 64px;
      height: 64px;
      border-radius: 50%;
    }
  }
  .profile_username {
    width: 100%;
    height: 48px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    color: @darkTextColor3;
  }
  .profile_footer {
    position: absolute;
    width: 100%;
    height: 96px;
    left: 0;
    bottom: 0;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }
  .tab_inner {
    position: relative;
    width: 100%;
    height: calc(~"100% - 36px");
    // display: flex;
    // flex-direction: row;
    // align-items: center;
    // justify-content: center;
    .profile_left {
      position: absolute;
      left: 0;
      width: 200px;
      height: 100%;
      box-shadow: -20px -5px 22px -22px rgba(217, 217, 217, 0.8) inset;
      background-color: lighten(@darkDividerColor, 85);
    }
    .profile_right {
      position: absolute;
      left: 200px;
      width: calc(~"100% - 200px");
      height: 100%;
    }
  }
  .register_box {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 999;
    width: 100%;
    height: 100%;
    transform: scale(0);
    &_mask {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      opacity: 0;
      transition: opacity 2s ease-in-out;
    }
    &_content {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: calc(~"100% - 20px");
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      &_inner {
        position: relative;
        width: 240px;
        // height: 320px;
        background: url(http://static.dei2.com/resources/bg.png) no-repeat 100%
          20%;
        border-radius: 8px;
        transition: all 0.2s ease-in-out;
        transform: translate3d(0, 800px, 0);
        .close_btn {
          position: absolute;
          right: -30px;
          top: -30px;
          width: 32px;
          height: 32px;
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          svg {
            width: 24px;
            height: 24px;
            fill: @darkTextColor3;
          }
        }
      }
    }
  }
}
</style>